package com.sjy.project.ent.test;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javafx.util.Pair;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "亩均接口相关", tags = {"亩均测试接口"})
@RequestMapping({"/api/mujun/test"})
public class TController {


    private String userUrl = "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220309000001/rest/user/query";

    private String access_key = "BCDSGA_8cae724a0bee4c804d7b94db84f2827c";

    private String secret_key = "BCDSGS_9c23732165e0cb3bab9c218adf57ff14";


    @ApiOperation(value = "100.测试", position = 100,notes = "sso测试")
	@SuppressWarnings("unchecked")
	@ApiImplicitParams({
	})
    @PostMapping("/noToken/login")
    public String login(String ssotoken,String ssoticket, HttpServletRequest request) throws MalformedURLException, URISyntaxException, NoSuchAlgorithmException, InvalidKeyException {
        String token =  ssotoken;//request.getParameter("ssotoken");
        String ticker =  ssoticket;//request.getParameter("ssoticket");
        System.out.println(token);
        RestTemplate restTemplate = new RestTemplate();
        //设置请求头信息
        DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(new Date());
        URL url = new URL(userUrl);
        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
        String canonicalQueryString = getCanonicalQueryString(uri.getQuery());
        String message = "POST" + "\n" + "/restapi/prod/IC33000020220309000001/rest/user/query" + "\n" + canonicalQueryString + "\n"  + access_key + "\n" + date + "\n";
        Mac hasher = Mac.getInstance("HmacSHA256");
        hasher.init(new SecretKeySpec(secret_key.getBytes(), "HmacSHA256"));
        byte[] hash = hasher.doFinal(message.getBytes());
        DatatypeConverter.printHexBinary(hash);
        String sign = DatatypeConverter.printBase64Binary(hash);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.set("X-BG-HMAC-SIGNATURE",sign);
        httpHeaders.set("X-BG-HMAC-ALGORITHM","hmac-sha256");
        httpHeaders.set("X-BG-HMAC-ACCESS-KEY",access_key);
        httpHeaders.set("X-BG-DATE-TIME",date);
        System.out.println(sign);
        System.out.println(date);
        //发送请求头格式 为json/编码为utf-8
        httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        //将请求对象转换成json对象 ，后面加设置的请求信息
        JSONObject json = new JSONObject();
        json.put("token",token);
        HttpEntity<String> entity=new HttpEntity<String>(json.toJSONString(),httpHeaders);
        String a = restTemplate.exchange(userUrl, HttpMethod.POST,entity,String.class).getBody();
        return a;
    }




    private static String getCanonicalQueryString(String query) {
        if (query == null || query.trim().length() == 0) {
            return "";
        }
        List<Pair<String, String>> queryParamList = new ArrayList<>();
        String[] params = query.split("&");
        for (String param : params) {
            int eqIndex = param.indexOf("=");
            String key = param.substring(0, eqIndex);
            String value = param.substring(eqIndex+1);
            Pair<String, String> pair = new Pair<String, String>(key,value);
            queryParamList.add(pair);
        }

        List<Pair<String, String>> sortedParamList = queryParamList.stream().sorted(Comparator.comparing(param -> param.getKey() + "=" + Optional.ofNullable(param.getValue()).orElse(""))).collect(Collectors.toList());
        List<Pair<String, String>> encodeParamList = new ArrayList<>();
        sortedParamList.stream().forEach(param -> {
            try {
                String key = URLEncoder.encode(param.getKey(), "utf-8");
                String value = URLEncoder.encode(Optional.ofNullable(param.getValue()).orElse(""), "utf-8")
                        .replaceAll("\\%2B","%20")
                        .replaceAll("\\+","%20")
                        .replaceAll("\\%21","!")
                        .replaceAll("\\%27","'")
                        .replaceAll("\\%28","(")
                        .replaceAll("\\%29",")")
                        .replaceAll("\\%7E","~")
                        .replaceAll("\\%25","%")
                        ;
                encodeParamList.add(new Pair<>(key, value));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("encoding error");
            }
        });
        StringBuilder queryParamString = new StringBuilder(64);
        for (Pair<String, String> encodeParam : encodeParamList) {
            queryParamString.append(encodeParam.getKey()).append("=").append(Optional.ofNullable(encodeParam.getValue()).orElse(""));
            queryParamString.append("&");
        }

        return queryParamString.substring(0, queryParamString.length() - 1);
    }
    
    public static void main(String[] args) {
    	Integer max = Integer.MAX_VALUE;
    	for(int i=1;i<max;i++) {
    		if(i%3==1&&i%5==3&&i%7==5) {
    			System.out.println(i);
    		}
    	}
    }

}
